<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>深拷贝和浅拷贝</title>
</head>
<body>
<script>
    let a = {
        name: "哈哈",
        age: 18,
        arr: [1,2,3,4],
        fn: function(){},
        UNDEFINED: undefined,
        NULL: null,
        str: "",
    }
    //
    // let b = a;
    // b.name = "呵呵";
    // console.log(a);//"呵呵"
    // console.log(b);//"呵呵"

    //数据类型深拷贝和浅拷贝主要针对引用数据类型来说的

    //浅拷贝 只拷贝第一层
    //1 for in
    // let b = {};
    // for (let key in a){
    //     if(!a.hasOwnProperty(key)) continue;
    //     b[key] = a[key]
    // }
    // b.name = "呵呵";
    // console.log(a);
    // console.log(b);

    //2 Object.assign 把目标对象与原始对象进行合并 语法 Object.assign(原始对象,目标对象)
    // let b = {};
    // // let b = Object.assign({},a)
    // Object.assign(b,a)
    // b.name = "呵呵";
    // b.arr[0] = 1000;
    // console.log(a);
    // console.log(b);

    //深拷贝 层层拷贝
    // let b = JSON.parse(JSON.stringify(a));
    // b.name = "呵呵";
    // b.arr[0] = 1000;
    // console.log(a);
    // console.log(b);
    //问题  无法拷贝function和undefined

    //手动实现深拷贝

    // let a = {
    //     name: "哈哈",
    //     age: 18,
    //     arr: [1,2,3,4],
    //     fn: function(){},
    //     UNDEFINED: undefined,
    //     NULL: null,
    //     str: "",
    // }
    function deepClone(obj){
        //当obj值为基本数据类型的时候 直接返回
        if(typeof obj !== "object" || obj === null){
            return obj
        }
        //当obj不是基本数据类型的时候
        /*let result;
        if(obj instanceof Array){
            result = [];
        }else {
            result = {};
        }*/
        let result = obj instanceof Array?[]:{}
        for (let key in obj){
            //语法: 判断属性名是否为当前对象的私有属性  当前对象.hasOwnProperty(属性名)
            if(!obj.hasOwnProperty(key)) continue;
            result[key] = deepClone(obj[key])
        }
        return result
    }

    let b = deepClone(a);
    b.name = "呵呵";
    b.arr[0] = 1000;
    console.log(a);
    console.log(b);





</script>
</body>
</html>